package com.gr;

import com.gr.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//@Component//测试
public class CheckLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //提前判断是否是user模块请求
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();//请求路径
        if (uri.indexOf("/user-module/")>-1){//判断字符串下标，判断请求路径是否有usermodule
            return chain.filter(exchange);//放行请求
        }
        //1.获取请求头中的token
        List<String> authorization = request.getHeaders().get("authorization");//可能有两个键对应两个值所以是list
        if (authorization!=null&&authorization.size()>0){
            String token = authorization.get(0);
            //2.判断token是否正确
            try {
                JwtUtils.verify(token);
                return chain.filter(exchange);////4.否则放行请求
            }catch (Exception e){ //3.如果有异常就通知前端没有权限
                //拦截
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }else {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }



    }


    @Override
    public int getOrder() {//拦截顺序
        return 0;
    }
}
